import { inject, Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { ActivatedRoute, Router } from "@angular/router";
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzNotificationService } from 'ng-zorro-antd/notification';


@Injectable()
export class HttpStatusCodeInterceptor implements HttpInterceptor {

  // logService: LogService = inject(LogService);

  router: Router = inject(Router);
  private notification: NzNotificationService = inject(NzNotificationService);

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // const copyReq = req.clone({
    //   headers: req.headers.set('token', 'my-auth-token'),
    // });
    //请求拦截
    return next.handle(req).pipe(
      tap(
        //响应拦截
        event => {
          console.log(event);
          if (event instanceof HttpResponse) {
            if (event.status == 500) {
              this.notification.create(
                'error',
                '全局拦截',
                '服务器繁忙，请稍后'
              );
              // 跳转错误页面
              this.router.navigateByUrl("/login").then(r => { console.log(r) })

            }
            if (event.status >= 500) {
              console.log('服务器异常了')
              this.notification.create(
                'error',
                '全局拦截',
                '服务器繁忙，请稍后'
              );
            }
          }
        },
        error => {
          console.log(error);
          // token过期 服务器错误等处理
          this.router.navigateByUrl("/study/login").then(r => { console.log(r) })
        })
    );
  }
}
